﻿using BW.Mes.WinForms.Process;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO; // 添加这个引用来使用File类
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Web.UI;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.CustomerForm;

namespace BW.Mes.WinForms.Production.Order
{
    public partial class OrderForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _workorderApiBaseUrl = "http://120.26.197.100:8022";
        private readonly string _basedataUrl = "http://120.26.197.100:8022";
        private List<WorkOrderModel> _allWorkOrders; // 存储所有数据
        private RepositoryItemPictureEdit _pictureEdit; // 添加图片编辑器控件
        // 七牛云配置
        private readonly string accessKey = "s93QzD2kkEcPpdLa4fHcJpxFA4ULq0C01udjmtJN";
        private readonly string secretKey = "aR3LQgh67jWpHDF-2sTcMSBWuTuwiUhdglmLAffF";
        private readonly string bucket = "xyf-img";
        private readonly string domain = "syv7j21aq.hb-bkt.clouddn.com"; // 七牛云存储域名
        private readonly string _qiniuPrefix = "Pic/"; // 七牛云存储前缀目录
        private readonly int _imageTimeoutSeconds = 30; // 图片加载超时时间

        /// <summary>
        /// 扩展WebClient以支持超时设置
        /// </summary>
        private class WebClientWithTimeout : WebClient
        {
            private int _timeout = 60000; // 默认60秒

            public int Timeout
            {
                get { return _timeout; }
                set { _timeout = value; }
            }

            protected override WebRequest GetWebRequest(Uri uri)
            {
                WebRequest request = base.GetWebRequest(uri);
                if (request != null)
                {
                    request.Timeout = _timeout;
                }
                return request;
            }
        }


        // 添加简单的ProcessModel类定义
        public class ProcessModel
        {
            public long Id { get; set; }
            public string ProcessName { get; set; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public OrderForm()
        {
            InitializeComponent();

            _httpClient = new HttpClient();
            _basedataUrl = "http://120.26.197.100:8022";

            // 配置GridControl的基本设置
            gridControl1.UseEmbeddedNavigator = false;
            gridView1.OptionsView.ColumnAutoWidth = false; // 禁用列自动宽度
            gridView1.OptionsView.RowAutoHeight = true; // 允许行高自动调整

            // 确保操作列配置正确
            ConfigureOperationColumn();

            // 配置图片列
            ConfigureImageColumn();

            // 配置日期控件，只显示日期部分
            time_createat.Properties.DisplayFormat.FormatString = "yyyy-MM-dd";
            time_createat.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            time_createat.Properties.EditFormat.FormatString = "yyyy-MM-dd";
            time_createat.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            time_createat.Properties.Mask.EditMask = "yyyy-MM-dd";
            time_createat.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
            time_createat.Properties.VistaDisplayMode = DevExpress.Utils.DefaultBoolean.True;
            time_createat.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.False;

            // 绑定查询按钮点击事件
            simpleButton1.Click += simpleButton1_Click;

            //加载
            this.Load += gridControl1_Load;

            // 设置默认每页显示条数为3
            userControl11.PageSize = 3;

            // 注册分页控件事件
            userControl11.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            userControl11.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            userControl11.JumpPageEvent += UserControl1_JumpPageEvent;




            //父子级
            this.IsMdiContainer = false;
        }

        /// <summary>
        /// 配置图片列
        /// </summary>
        private void ConfigureImageColumn()
        {
            try
            {
                // 创建图片编辑器
                _pictureEdit = new RepositoryItemPictureEdit();
                _pictureEdit.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
                _pictureEdit.NullText = "";

                // 将图片编辑器添加到GridControl的RepositoryItems中
                gridControl1.RepositoryItems.Add(_pictureEdit);

                // 设置Img列使用图片编辑器
                if (gridView1.Columns["Img"] != null)
                {
                    gridView1.Columns["Img"].ColumnEdit = _pictureEdit;
                    gridView1.Columns["Img"].Width = 100;
                    gridView1.Columns["Img"].FieldName = "Img";
                    gridView1.OptionsView.RowAutoHeight = true;
                }

                // 添加自定义显示事件
                gridView1.CustomColumnDisplayText += GridView1_CustomRowCellDisplayText;

                // 添加自定义绘制事件
                gridView1.CustomDrawCell += gridView1_CustomDrawCell;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"配置图片列时出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridView1_CustomRowCellDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "Img")
            {
                // 防止显示URL文本
                e.DisplayText = "";
            }
        }

        /// <summary>
        /// 配置操作列和按钮编辑器
        /// </summary>
        private void ConfigureOperationColumn()
        {
            try
            {
                // 确保操作列的FieldName为空，避免数据绑定错误
                if (gridView1.Columns["operation"] != null)
                {
                    gridView1.Columns["operation"].FieldName = "";
                    gridView1.Columns["operation"].UnboundType = DevExpress.Data.UnboundColumnType.String;
                    gridView1.Columns["operation"].Width = 100;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"配置操作列时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 显示数据的方法（加载）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void gridControl1_Load(object sender, EventArgs e)
        {
            await LoadWorkOrder();
            DisplayPagedData();
            await ShowClient();
        }

        /// <summary>
        /// 添加工单的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddOrder_Click(object sender, EventArgs e)
        {
            var addOrder = new AddOrederForm();
            addOrder.ShowDialog(); // 这是弹出，不是跳转
            await LoadWorkOrder();
            DisplayPagedData();
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询条件
                string orderCode = txt_code.Text.Trim();

                // 安全获取客户ID
                long? orderClient = null;
                if (grid_client.EditValue != null)
                {
                    if (long.TryParse(grid_client.EditValue.ToString(), out long clientId) && clientId > 0)
                    {
                        orderClient = clientId;
                    }
                }

                // 获取创建时间 - 只取日期部分，不包含时间
                DateTime? createTime = null;
                if (time_createat.EditValue != null && time_createat.EditValue is DateTime date)
                {
                    // 只保留年月日，时分秒设为0
                    createTime = new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
                }

                // 显示查询中的提示
                this.Cursor = Cursors.WaitCursor;

                try
                {
                    // 调用显示数据方法，传递条件
                    await ShowData(orderCode, orderClient, createTime, 1); // 查询时回到第一页
                }
                finally
                {
                    // 恢复鼠标指针
                    this.Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询操作失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 显示查询数据方法
        /// </summary>
        /// <param name="orderCode"></param>
        /// <param name="orderClient"></param>
        /// <param name="createTime"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        private async Task ShowData(string orderCode, long? orderClient, DateTime? createTime, int page)
        {
            try
            {
                // 拼接API路径
                string queryParams = "";

                if (!string.IsNullOrEmpty(orderCode))
                {
                    queryParams += $"Code={WebUtility.UrlEncode(orderCode)}&";
                }

                if (orderClient.HasValue && orderClient.Value > 0)
                {
                    queryParams += $"Client={orderClient.Value}&";
                }

                if (createTime.HasValue)
                {
                    // 只使用日期部分，格式为yyyy-MM-dd
                    var formattedDate = createTime.Value.ToString("yyyy-MM-dd");
                    queryParams += $"CreatedAt={WebUtility.UrlEncode(formattedDate)}&";

                    // 打印日志，确认查询参数
                    Console.WriteLine($"查询日期: {formattedDate}");
                }

                if (!string.IsNullOrEmpty(queryParams))
                {
                    queryParams = "?" + queryParams.TrimEnd('&');
                }

                // 打印完整查询URL
                Console.WriteLine($"查询URL: T4/ProduceModel/GetWorkOrder{queryParams}");

                // 获取数据
                _allWorkOrders = await GetApiDataAsync<List<WorkOrderModel>>($"T4/ProduceModel/GetWorkOrder{queryParams}");

                // 确保返回的数据不为null
                if (_allWorkOrders == null)
                {
                    _allWorkOrders = new List<WorkOrderModel>();
                    MessageBox.Show("未获取到数据，请检查查询条件或网络连接", "提示");
                }

                // 计算总页数
                int totalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
                if (totalPages < 1) totalPages = 1;

                // 确保页码有效
                if (page > totalPages)
                {
                    page = totalPages;
                }

                // 更新分页控件
                userControl11.CurrentPage = page;
                userControl11.TotalRows = _allWorkOrders.Count;
                userControl11.TotalPages = totalPages;
                userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";

                // 显示当前页数据
                DisplayPagedData();

                // 如果没有数据，显示提示
                if (_allWorkOrders.Count == 0)
                {
                    XtraMessageBox.Show("未查询到符合条件的数据", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询数据时出错: {ex.Message}", "错误");
                _allWorkOrders = new List<WorkOrderModel>();
                DisplayPagedData();
            }
        }


        /// <summary>
        /// 客户下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowClient()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_basedataUrl}/T2/Customer/GetCustomer");
                response.EnsureSuccessStatusCode();


                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var process = JsonConvert.DeserializeObject<List<CustomerModel>>(dataJson);

                    // 设置数据源
                    grid_client.Properties.DataSource = process;
                    // 在加载产线数据时
                    grid_client.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                    grid_client.Properties.DisplayMember = "CustomerName";  // 数据源中的显示文本字段名
                    grid_client.Properties.NullText = "请选择所属客户";

                    // 配置GridLookUpEdit的列 - 使用正确的方式
                    if (grid_client.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                    {
                        // 清除现有列
                        gridView.Columns.Clear();

                        // 添加产线名称列
                        DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                        nameColumn.Caption = "客户名称";
                        nameColumn.FieldName = "CustomerName";
                        nameColumn.Visible = true;
                        nameColumn.VisibleIndex = 0;

                        // 可选：设置列宽
                        nameColumn.Width = 150;

                        // 添加列到网格视图
                        gridView.Columns.Add(nameColumn);

                        // 禁用网格视图的分组面板
                        gridView.OptionsView.ShowGroupPanel = false;

                        // 设置行焦点样式
                        gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                        // 禁用单元格焦点外观
                        gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载客户数据失败: {ex.Message}", "错误");
                throw;
            }

        }


        /// <summary>
        /// 加载
        /// </summary>
        /// <returns></returns>
        private async Task LoadWorkOrder()
        {
            try
            {
                _allWorkOrders = await GetApiDataAsync<List<WorkOrderModel>>("T4/ProduceModel/GetWorkOrder");

                // 确保_allWorkOrders不为null
                if (_allWorkOrders == null)
                {
                    _allWorkOrders = new List<WorkOrderModel>();
                    MessageBox.Show("未能获取到工单数据，返回结果为空", "提示");
                }

                // 设置总记录数和总页数
                int totalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
                userControl11.TotalRows = _allWorkOrders.Count;
                userControl11.TotalPages = totalPages;
                userControl11.CurrentPage = 1; // 加载数据时重置为第一页

                // 更新页码信息标签
                userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";

                // 为所有数据设置操作列的值
                foreach (var item in _allWorkOrders)
                {
                    // 确保每一项不为null
                    if (item != null)
                    {
                        item.operation = ""; // 设置为空字符串，使按钮显示
                    }
                }

                // 显示分页数据
                DisplayPagedData();
            }
            catch (Exception ex)
            {
                _allWorkOrders = new List<WorkOrderModel>(); // 确保发生异常时也有一个空列表
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                DisplayPagedData(); // 即使出错也尝试显示（会显示空数据）
            }
        }
        /// <summary>
        /// 显示分页后的数据
        /// </summary>
        private void DisplayPagedData()
        {
            if (_allWorkOrders == null || _allWorkOrders.Count == 0)
            {
                // 清空数据源，显示空列表
                gridControl1.DataSource = null;

                // 刷新网格视图
                gridView1.RefreshData();

                // 显示提示信息
                XtraMessageBox.Show("没有符合条件的数据", "提示");
                return;
            }

            // 计算总页数并更新分页控件
            int totalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
            userControl11.TotalPages = totalPages;
            userControl11.TotalRows = _allWorkOrders.Count;

            // 确保当前页不超过总页数
            if (userControl11.CurrentPage > totalPages)
            {
                userControl11.CurrentPage = totalPages;
            }

            // 更新页码显示
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{totalPages}页";

            int startIndex = (userControl11.CurrentPage - 1) * userControl11.PageSize;
            int count = Math.Min(userControl11.PageSize, _allWorkOrders.Count - startIndex);

            if (startIndex < 0 || count <= 0)
            {
                // 清空数据源，显示空列表
                gridControl1.DataSource = null;
                gridView1.RefreshData();
                return;
            }

            // 获取当前页的数据
            var pagedData = _allWorkOrders.Skip(startIndex).Take(count).ToList();

            // 设置每个行项目的操作列值为空字符串（按钮用）
            foreach (var item in pagedData)
            {
                item.operation = "";  // 确保操作列有值但显示为按钮

                // 处理图片路径 - 简化七牛云URL处理
                if (!string.IsNullOrEmpty(item.Img))
                {
                    // 保存原始路径
                    string originalImg = item.Img;

                    try
                    {
                        // 如果已经是七牛云的完整URL，直接使用
                        if (item.Img.StartsWith("http"))
                        {
                            // 已经是完整URL，不需要修改
                            // 预处理可能存在的token参数
                            item.Img = ProcessImageUrl(item.Img);
                        }
                        else
                        {
                            // 如果是文件名或相对路径，构建标准七牛云URL
                            string fileName = Path.GetFileName(item.Img);
                            item.Img = ProcessImageUrl($"http://{domain}/{_qiniuPrefix}{fileName}");
                            Console.WriteLine($"构建七牛云图片URL: {item.Img}");
                        }

                        // 预加载图片到缓存
                        PreloadImage(item.Img);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"处理图片路径出错: {ex.Message}, 原始路径: {originalImg}");
                        // 出错时恢复原始路径
                        item.Img = originalImg;
                    }
                }
            }

            // 绑定到GridControl
            gridControl1.DataSource = null;
            gridControl1.DataSource = pagedData;

            // 配置GridControl的滚动条设置
            gridControl1.UseEmbeddedNavigator = false;
            gridView1.OptionsView.ColumnAutoWidth = false; // 禁用列自动宽度

            // 确保所有列的FieldName与数据模型属性名匹配
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
            {
                // 根据列名设置正确的FieldName
                switch (col.Name)
                {
                    case "Code": col.FieldName = "Code"; break;
                    case "ProductionType": col.FieldName = "ProductionType"; break;
                    case "CustomerName": col.FieldName = "CustomerName"; break;
                    case "ProductName": col.FieldName = "ProductName"; break;
                    case "LineName": col.FieldName = "LineName"; break;
                    case "ProcessName": col.FieldName = "ProcessName"; break;
                    case "OperationName": col.FieldName = "OperationName"; break;
                    case "State": col.FieldName = "State"; break;
                    case "Ids": col.FieldName = "IsSelected"; break;
                    case "Progress": col.FieldName = "Progress"; break;
                    case "ProductionCount": col.FieldName = "ProductionCount"; break;
                    case "BeginTime": col.FieldName = "BeginTime"; break;
                    case "EndTime": col.FieldName = "EndTime"; break;
                    case "Whether": col.FieldName = "Whether"; break;
                    case "Img": col.FieldName = "Img"; break;
                    case "ProductionDesc": col.FieldName = "ProductionDesc"; break;
                    case "Input": col.FieldName = "Input"; break;
                    case "Good": col.FieldName = "Good"; break;
                    case "Scrap": col.FieldName = "Scrap"; break;
                    case "Source": col.FieldName = "Source"; break;
                    case "ProductionNumber": col.FieldName = "ProductionNumber"; break;
                    case "CreatedBy": col.FieldName = "CreatedBy"; break;
                    case "CreatedAt": col.FieldName = "CreatedAt"; break;
                    case "operation": col.FieldName = ""; break; // 操作列使用空字段名
                }

                // 确保所有列都是可见的
                col.Visible = true;

                // 设置更宽的列宽
                col.Width = 150; // 将默认列宽从100增加到150

                // 根据列内容类型设置不同的宽度
                switch (col.FieldName)
                {
                    case "IsSelected": col.Width = 60; break; // 选择框列宽较小
                    case "Code": col.Width = 120; break;
                    case "CustomerName": col.Width = 180; break;
                    case "ProductName": col.Width = 200; break;
                    case "LineName": col.Width = 150; break;
                    case "ProcessName": col.Width = 180; break;
                    case "Img": col.Width = 120; break;
                    case "ProductionDesc": col.Width = 200; break; // 描述列宽度更大
                    case "CreatedAt":
                    case "BeginTime":
                    case "EndTime": col.Width = 160; break; // 日期时间列宽度更大
                }
            }

            // 不再调用BestFitColumns，因为我们手动设置了列宽
            // gridView1.BestFitColumns();

            // 添加安全检查，确保operation列存在
            try
            {
                if (gridView1.Columns["operation"] != null)
                {
                    // 设置操作列的宽度
                    gridView1.Columns["operation"].Width = 100; // 设置适当的宽度
                    // 设置操作列不自动调整大小
                    gridView1.OptionsView.ColumnAutoWidth = false;
                    gridView1.Columns["operation"].OptionsColumn.AllowSize = false;
                }

                // 确保图片列配置正确 - 使用标准设置
                if (gridView1.Columns["Img"] != null)
                {
                    // 停止使用PictureEdit控件，改为自定义绘制
                    gridView1.Columns["Img"].ColumnEdit = null;
                    gridView1.Columns["Img"].Width = 100;
                    gridView1.OptionsView.RowAutoHeight = true; // 允许行高自动调整以适应图片
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不中断执行
                Console.WriteLine($"设置列属性时出错: {ex.Message}");
            }

            gridView1.RefreshData();
            gridView1.LayoutChanged();
        }


        /// <summary>
        /// 页码按钮点击事件处理
        /// </summary>
        /// <param name="currentPage"></param>
        private async void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            // 更新当前页码
            userControl11.CurrentPage = currentPage;

            // 更新页码信息显示
            userControl11.PageInfo.Text = $"第{currentPage}/{userControl11.TotalPages}页";

            // 显示当前页数据
            DisplayPagedData();
        }

        /// <summary>
        /// 每页显示条数改变事件处理
        /// </summary>
        private void UserControl1_ChangedPageSizeEvent()
        {
            // 重新计算总页数
            int totalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
            if (totalPages < 1) totalPages = 1;

            // 确保当前页不超过总页数
            if (userControl11.CurrentPage > totalPages)
            {
                userControl11.CurrentPage = totalPages;
            }

            // 更新分页控件
            userControl11.TotalPages = totalPages;
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{totalPages}页";

            // 显示当前页数据
            DisplayPagedData();
        }

        /// <summary>
        /// 跳转页面事件处理
        /// </summary>
        /// <param name="jumpPage"></param>
        private void UserControl1_JumpPageEvent(int jumpPage)
        {
            // 确保跳转页码有效
            if (jumpPage < 1)
            {
                jumpPage = 1;
            }
            else if (jumpPage > userControl11.TotalPages)
            {
                jumpPage = userControl11.TotalPages;
            }

            // 更新当前页码
            userControl11.CurrentPage = jumpPage;

            // 更新页码信息显示
            userControl11.PageInfo.Text = $"第{jumpPage}/{userControl11.TotalPages}页";

            // 显示当前页数据
            DisplayPagedData();
        }

        /// <summary>
        /// 获取工单数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {

                // 创建HttpClientHandler并配置SSL证书验证
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true // 忽略SSL证书错误
                };

                // 创建新的HttpClient实例，使用自定义handler
                using (var client = new HttpClient(handler))
                {
                    try
                    {
                        // 设置超时时间
                        client.Timeout = TimeSpan.FromSeconds(30);

                        // 设置请求头
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                        // 显示请求URL，便于调试
                        string requestUrl = $"{_workorderApiBaseUrl}/{endpoint}";

                        HttpResponseMessage response;
                        try
                        {
                            response = await client.GetAsync(requestUrl);
                            response.EnsureSuccessStatusCode();
                        }
                        catch (HttpRequestException httpEx)
                        {
                            Console.WriteLine($"HTTP请求错误: {httpEx.Message}");
                            MessageBox.Show($"HTTP请求错误: {httpEx.Message}", "网络错误");
                            return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                        }

                        string responseBody;
                        try
                        {
                            responseBody = await response.Content.ReadAsStringAsync();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"读取响应内容时出错: {ex.Message}");
                            MessageBox.Show($"读取响应内容时出错: {ex.Message}", "错误");
                            return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                        }
                        // 检查响应内容是否为空
                        if (string.IsNullOrWhiteSpace(responseBody))
                        {
                            MessageBox.Show("API返回的数据为空", "警告");
                            return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                        }

                        try
                        {
                            Console.WriteLine("开始解析JSON响应");

                            // 尝试直接反序列化为目标类型
                            try
                            {
                                var directResult = JsonConvert.DeserializeObject<T>(responseBody);
                                if (directResult != null)
                                {
                                    if (directResult is List<WorkOrderModel> directWorkOrders)
                                    {
                                        Console.WriteLine($"直接反序列化成功获取{directWorkOrders.Count}条工单数据");
                                    }
                                    return directResult;
                                }
                            }
                            catch (JsonException ex)
                            {
                                Console.WriteLine($"直接反序列化失败，尝试解析为JObject: {ex.Message}");
                            }

                            // 如果直接反序列化失败，尝试解析为JObject
                            Newtonsoft.Json.Linq.JObject jsonObject;
                            try
                            {
                                jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                            }
                            catch (JsonException ex)
                            {
                                Console.WriteLine($"JSON解析为JObject失败: {ex.Message}");
                                MessageBox.Show($"JSON解析错误: {ex.Message}", "JSON错误");
                                return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                            }

                            var propertyNames = string.Join(", ", jsonObject.Properties().Select(p => p.Name));
                            Console.WriteLine($"JSON解析成功，包含以下属性: {propertyNames}");

                            // 尝试从各种可能的属性中提取数据
                            string dataJson = null;
                            if (jsonObject["PageDate"] != null)
                            {
                                dataJson = jsonObject["PageDate"].ToString();
                            }
                            else if (jsonObject["Data"] != null)
                            {
                                dataJson = jsonObject["Data"].ToString();
                            }
                            else if (jsonObject["data"] != null)
                            {
                                dataJson = jsonObject["data"].ToString();
                            }
                            else if (jsonObject["Result"] != null)
                            {
                                dataJson = jsonObject["Result"].ToString();
                            }
                            else if (jsonObject["result"] != null)
                            {
                                dataJson = jsonObject["result"].ToString();
                            }
                            else if (jsonObject["Items"] != null)
                            {
                                dataJson = jsonObject["Items"].ToString();
                            }
                            else if (jsonObject["items"] != null)
                            {
                                dataJson = jsonObject["items"].ToString();
                            }

                            if (dataJson != null)
                            {
                                Console.WriteLine($"提取的数据字段: {dataJson.Substring(0, Math.Min(100, dataJson.Length))}...");

                                try
                                {
                                    var result = JsonConvert.DeserializeObject<T>(dataJson);
                                    if (result != null)
                                    {
                                        if (result is List<WorkOrderModel> workOrders)
                                        {
                                            Console.WriteLine($"成功获取{workOrders.Count}条工单数据");
                                        }
                                        return result;
                                    }
                                    else
                                    {
                                        Console.WriteLine("数据字段反序列化结果为null");
                                    }
                                }
                                catch (JsonException ex)
                                {
                                    Console.WriteLine($"数据字段反序列化失败: {ex.Message}");
                                }
                            }
                            else
                            {
                                Console.WriteLine("未找到数据字段，尝试直接使用整个响应");
                            }

                            // 如果所有尝试都失败，返回默认值
                            Console.WriteLine("所有反序列化尝试都失败，返回空列表");
                            return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理JSON数据时出现未预期的错误: {ex.Message}");
                            MessageBox.Show($"处理JSON数据时出现错误: {ex.Message}", "错误");
                            return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"HTTP客户端操作时出错: {ex.Message}");
                        MessageBox.Show($"HTTP客户端操作时出错: {ex.Message}", "错误");
                        return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取数据失败: {ex.Message}\n{ex.StackTrace}");
                MessageBox.Show($"获取数据失败: {ex.Message}", "错误");
                return typeof(T) == typeof(List<WorkOrderModel>) ? (T)(object)new List<WorkOrderModel>() : default;
            }
        }

        /// <summary>
        /// 定义数据模型类
        /// </summary>
        public class WorkOrderModel
        {
            [DisplayName("选择")]
            public bool IsSelected { get; set; }
            [DisplayName("编号")]
            public long Id { get; set; }

            [DisplayName("编号")]
            public string Code { get; set; }

            [DisplayName("生产类型")]
            public string ProductionType { get; set; }

            [DisplayName("客户id")]
            public long Client { get; set; }
            /// <summary>
            /// 客户名称
            /// </summary>
            [DisplayName("客户")]
            public string CustomerName { get; set; }


            [DisplayName("产品主数据Id")]
            public long Masterdata { get; set; }
            // 产品主数据名称
            [DisplayName("产品主数据")]
            public string ProductName { get; set; }

            [DisplayName("产线id")]
            public long Line { get; set; }
            [DisplayName("产线")]
            public string LineName { get; set; }

            [DisplayName("工序路线id")]
            public long Operation { get; set; }
            //工序路线
            [DisplayName("工序路线")]
            public string OperationName { get; set; }



            [DisplayName("状态")]
            public string State { get; set; }

            [DisplayName("生产进度")]
            public string Progress { get; set; }

            [DisplayName("生产数量")]
            public int ProductionCount { get; set; }

            [DisplayName("开始时间")]
            public DateTime BeginTime { get; set; }

            [DisplayName("结束时间")]
            public DateTime EndTime { get; set; }

            [DisplayName("是否允许")]
            public string Whether { get; set; }

            [DisplayName("上传文件")]
            public string Img { get; set; }

            [DisplayName("生产描述")]
            public string ProductionDesc { get; set; }

            [DisplayName("输入数量")]
            public int Input { get; set; }

            [DisplayName("良品数量")]
            public int Good { get; set; }

            [DisplayName("报废数量")]
            public int Scrap { get; set; }

            [DisplayName("来源")]
            public string Source { get; set; }

            [DisplayName("生产单号")]
            public string ProductionNumber { get; set; }

            [DisplayName("创建人")]
            public string CreatedBy { get; set; }

            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; }

            // 不使用DisplayName特性，避免数据绑定到此属性
            // 这个属性只用于显示按钮
            public string operation { get; set; }
            public string step { get; set;}
        }
        /// <summary>
        /// 删除工单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DelOrder_Click(object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelected");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;

            // 创建HttpClientHandler并配置SSL证书验证
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender_, cert, chain, sslPolicyErrors) => true // 忽略SSL证书错误
            };

            using (var client = new HttpClient(handler) { BaseAddress = new Uri(_workorderApiBaseUrl) })
            {
                // 设置超时时间
                client.Timeout = TimeSpan.FromSeconds(30);

                // 设置请求头
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                foreach (var id in checkedIds)
                {
                    var resp = await client.PostAsync($"/T4/ProduceModel/DeleteWorkorder?id={id}", new StringContent("", Encoding.UTF8, "application/json"));
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }
            await LoadWorkOrder();
            XtraMessageBox.Show("删除完成！");
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ExportOrder_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建HttpClientHandler并配置SSL证书验证
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (sender_, cert, chain, sslPolicyErrors) => true // 忽略SSL证书错误
                };

                using (var client = new HttpClient(handler) { BaseAddress = new Uri(_workorderApiBaseUrl) })
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);

                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    // 创建保存对话框
                    SaveFileDialog saveDialog = new SaveFileDialog();
                    saveDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
                    saveDialog.FilterIndex = 1;
                    saveDialog.RestoreDirectory = true;
                    saveDialog.FileName = $"工单数据_{DateTime.Now:yyyyMMdd_HHmmss}";

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        string filePath = saveDialog.FileName;

                        // 调用API获取导出文件
                        var response = await client.GetAsync("/T4/ProduceModel/ExportWorkOrderToExcel");

                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

                            // 保存文件
                            File.WriteAllBytes(filePath, fileBytes);

                            XtraMessageBox.Show("数据已成功导出！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 询问是否打开导出的文件
                            if (XtraMessageBox.Show("是否打开导出的文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show($"导出失败：{response.ReasonPhrase}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复鼠标指针
                this.Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UpdateOrder_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前行的数据
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle >= 0)
                {
                    // 获取当前行的WorkOrderModel对象
                    WorkOrderModel model = gridView1.GetRow(rowHandle) as WorkOrderModel;
                    if (model != null)
                    {
                        // 打开修改窗体，并传递选中的工单数据
                        var updateForm = new UpdateOrderForm(model);

                        // 显示窗体并等待结果
                        DialogResult result = updateForm.ShowDialog();

                        // 如果修改成功，刷新数据
                        if (result == DialogResult.OK)
                        {
                            // 刷新数据
                            await LoadWorkOrder();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改工单出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 图片缓存字典
        /// </summary>
        private Dictionary<string, Image> _imageCache = new Dictionary<string, Image>();

        /// <summary>
        /// 预加载图片到缓存中
        /// </summary>
        private void PreloadImage(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
                return;

            // 已经在缓存中的图片不需要再次加载
            if (_imageCache.ContainsKey(imageUrl))
                return;

            // 创建后台线程加载图片
            Task.Run(() => LoadImageInBackground(imageUrl));
        }

        /// <summary>
        /// 处理七牛云图片URL，确保能正确处理带token参数的URL
        /// </summary>
        /// <param name="imageUrl">原始图片URL</param>
        /// <returns>处理后的URL</returns>
        private string ProcessImageUrl(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
                return imageUrl;

            try
            {
                // 记录原始URL进行调试
                Console.WriteLine($"处理图片URL: {imageUrl}");

                // 检查URL是否为七牛云域名
                bool isQiniuUrl = imageUrl.Contains("xyf-img.xy2022.cn") ||
                         imageUrl.Contains(domain) ||
                         imageUrl.Contains("bkt.clouddn.com");

                if (!isQiniuUrl)
                {
                    // 不是七牛云URL，直接返回
                    Console.WriteLine($"不是七牛云URL，直接返回: {imageUrl}");
                    return imageUrl;
                }

                // 如果URL已经包含token参数且格式正确，不需要进一步处理
                if (imageUrl.Contains("?e=") && imageUrl.Contains("&token="))
                {
                    // 验证URL格式是否正确
                    try
                    {
                        Uri uri = new Uri(imageUrl);
                        string query = uri.Query;

                        // 确保查询参数中包含e和token两个参数
                        if (query.Contains("e=") && query.Contains("token="))
                        {
                            Console.WriteLine($"URL已包含有效token参数，保持不变: {imageUrl}");
                            return imageUrl;
                        }
                    }
                    catch
                    {
                        // URL格式无效，需要进一步处理
                    }
                }

                // 提取基本URL部分（移除所有查询参数）
                string baseUrl;
                if (imageUrl.Contains("?"))
                {
                    baseUrl = imageUrl.Substring(0, imageUrl.IndexOf("?"));
                }
                else
                {
                    baseUrl = imageUrl;
                }

                // 删除URL中可能存在的不必要的双斜杠
                baseUrl = baseUrl.Replace("//", "/").Replace(":/", "://");

                // 确保URL格式正确
                if (!baseUrl.StartsWith("http"))
                {
                    baseUrl = "http://" + baseUrl;
                }

                // 如果URL不是以域名结尾，确保它是一个完整的路径
                if (!baseUrl.EndsWith(".cn") && !baseUrl.EndsWith(".com") && !baseUrl.EndsWith(".net"))
                {
                    // 确保URL指向有效的资源（如果没有文件扩展名，可能需要额外处理）
                    if (!baseUrl.EndsWith(".jpg") && !baseUrl.EndsWith(".png") &&
                        !baseUrl.EndsWith(".jpeg") && !baseUrl.EndsWith(".gif") &&
                        !baseUrl.EndsWith(".bmp") && !baseUrl.EndsWith(".webp"))
                    {
                        // 如果URL没有包含文件扩展名，可能是七牛云的处理参数被错误分离了
                        // 这里我们不做过多假设，直接使用清理过的URL
                    }
                }

                // 七牛云URL最终保持原样
                // 注：在实际情况中，如果需要动态生成带有token的URL，这里可以调用七牛云SDK
                // 但为了简单起见，我们在此处理中仅处理URL格式，不生成新token
                string finalUrl = baseUrl;

                Console.WriteLine($"处理后的URL: {finalUrl}");
                return finalUrl;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理图片URL时出错: {ex.Message}, URL: {imageUrl}");
                return imageUrl; // 出错时返回原始URL
            }
        }

        /// <summary>
        /// 在后台线程中加载图片
        /// </summary>
        private async Task LoadImageInBackground(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
            {
                Console.WriteLine("图片URL为空，无法加载");
                return;
            }

            try
            {
                Console.WriteLine($"开始加载图片: {imageUrl}");

                // 处理图片URL（确保能处理带token参数的URL）
                string processedUrl = ProcessImageUrl(imageUrl);

                Console.WriteLine($"处理后的图片URL: {processedUrl}");

                // 策略1: 使用HttpClient加载图片
                using (var client = new HttpClient())
                {
                    // 设置超时，防止长时间阻塞
                    client.Timeout = TimeSpan.FromSeconds(_imageTimeoutSeconds);

                    // 添加User-Agent头，避免某些CDN拒绝请求
                    client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

                    // 添加Accept头，指示服务器返回图片内容
                    client.DefaultRequestHeaders.Accept.ParseAdd("image/webp,image/apng,image/*,*/*;q=0.8");

                    // 添加Referer头，有些CDN会检查这个
                    client.DefaultRequestHeaders.Referrer = new Uri($"http://{domain}");

                    Console.WriteLine($"使用HttpClient尝试加载图片: {processedUrl}");

                    try
                    {
                        // 发送请求获取图片数据
                        byte[] imageData = await client.GetByteArrayAsync(processedUrl);
                        Console.WriteLine($"HttpClient成功下载图片数据，大小: {imageData.Length} 字节");

                        // 从字节数组创建图片
                        using (MemoryStream ms = new MemoryStream(imageData))
                        {
                            try
                            {
                                Image img = Image.FromStream(ms);
                                Console.WriteLine($"成功从数据创建图片，尺寸: {img.Width}x{img.Height}");

                                // 添加到缓存
                                lock (_imageCache)
                                {
                                    if (!_imageCache.ContainsKey(imageUrl))
                                    {
                                        _imageCache[imageUrl] = img;
                                        Console.WriteLine($"图片已添加到缓存: {imageUrl}");
                                    }
                                }

                                // 在UI线程上刷新视图
                                this.BeginInvoke(new Action(() =>
                                {
                                    gridView1.RefreshData();
                                    Console.WriteLine("UI已刷新以显示图片");
                                }));

                                return; // 成功加载，直接返回
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"从内存流创建图片失败: {ex.Message}");
                                // 继续尝试其他方法
                            }
                        }
                    }
                    catch (HttpRequestException ex)
                    {
                        Console.WriteLine($"HttpClient请求失败: {ex.Message}");

                        // 策略2: 使用WebClient作为备选方案
                        try
                        {
                            Console.WriteLine($"尝试使用WebClient作为备选方案");
                            using (WebClientWithTimeout webClient = new WebClientWithTimeout())
                            {
                                webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
                                webClient.Headers.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
                                webClient.Headers.Add("Referer", $"http://{domain}");

                                // 设置超时
                                webClient.Timeout = _imageTimeoutSeconds * 1000;

                                byte[] imageData = webClient.DownloadData(processedUrl);
                                Console.WriteLine($"WebClient成功下载图片数据，大小: {imageData.Length} 字节");

                                using (MemoryStream ms = new MemoryStream(imageData))
                                {
                                    try
                                    {
                                        Image img = Image.FromStream(ms);
                                        Console.WriteLine($"WebClient成功从数据创建图片，尺寸: {img.Width}x{img.Height}");

                                        lock (_imageCache)
                                        {
                                            if (!_imageCache.ContainsKey(imageUrl))
                                            {
                                                _imageCache[imageUrl] = img;
                                                Console.WriteLine($"WebClient图片已添加到缓存: {imageUrl}");
                                            }
                                        }

                                        this.BeginInvoke(new Action(() =>
                                        {
                                            gridView1.RefreshData();
                                            Console.WriteLine("WebClient: UI已刷新以显示图片");
                                        }));

                                        return; // 成功加载，直接返回
                                    }
                                    catch (Exception msEx)
                                    {
                                        Console.WriteLine($"WebClient从内存流创建图片失败: {msEx.Message}");
                                        // 继续尝试策略3
                                    }
                                }
                            }
                        }
                        catch (Exception webEx)
                        {
                            Console.WriteLine($"WebClient下载失败: {webEx.Message}");

                            // 策略3: 尝试最后一种方式 - 直接使用Bitmap加载
                            TryLoadWithBitmap(imageUrl, processedUrl);
                        }
                    }
                    catch (TaskCanceledException ex)
                    {
                        Console.WriteLine($"HttpClient请求超时: {ex.Message}");

                        // 超时后尝试使用WebClient或Bitmap
                        TryLoadWithWebClient(imageUrl, processedUrl);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"HttpClient其他错误: {ex.Message}");

                        // 其他异常，尝试WebClient或Bitmap
                        TryLoadWithWebClient(imageUrl, processedUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图片加载线程出现异常: {ex.Message}, 堆栈: {ex.StackTrace}");
                SetErrorImage(imageUrl);
            }
        }

        /// <summary>
        /// 尝试使用WebClient加载图片（辅助方法）
        /// </summary>
        private void TryLoadWithWebClient(string imageUrl, string processedUrl)
        {
            try
            {
                Console.WriteLine($"尝试使用WebClient加载: {processedUrl}");
                using (WebClientWithTimeout webClient = new WebClientWithTimeout())
                {
                    webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
                    webClient.Headers.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
                    webClient.Headers.Add("Referer", $"http://{domain}");

                    // 设置超时
                    webClient.Timeout = _imageTimeoutSeconds * 1000;

                    byte[] imageData = webClient.DownloadData(processedUrl);
                    using (MemoryStream ms = new MemoryStream(imageData))
                    {
                        Image img = Image.FromStream(ms);

                        lock (_imageCache)
                        {
                            if (!_imageCache.ContainsKey(imageUrl))
                            {
                                _imageCache[imageUrl] = img;
                            }
                        }

                        this.BeginInvoke(new Action(() => { gridView1.RefreshData(); }));
                    }
                }
            }
            catch (Exception webEx)
            {
                Console.WriteLine($"WebClient加载失败: {webEx.Message}");
                TryLoadWithBitmap(imageUrl, processedUrl);
            }
        }

        /// <summary>
        /// 尝试使用Bitmap直接加载图片（辅助方法）
        /// </summary>
        private void TryLoadWithBitmap(string imageUrl, string processedUrl)
        {
            try
            {
                Console.WriteLine($"尝试使用Bitmap直接加载: {processedUrl}");
                using (Bitmap bitmap = new Bitmap(processedUrl))
                {
                    Image img = new Bitmap(bitmap);

                    lock (_imageCache)
                    {
                        if (!_imageCache.ContainsKey(imageUrl))
                        {
                            _imageCache[imageUrl] = img;
                            Console.WriteLine($"Bitmap加载成功，已加入缓存: {imageUrl}");
                        }
                    }

                    this.BeginInvoke(new Action(() => { gridView1.RefreshData(); }));
                }
            }
            catch (Exception bitmapEx)
            {
                Console.WriteLine($"Bitmap加载失败: {bitmapEx.Message}");
                SetErrorImage(imageUrl);
            }
        }

        /// <summary>
        /// 设置错误占位图
        /// </summary>
        private void SetErrorImage(string imageUrl)
        {
            // 加载失败时，使用默认错误图标
            lock (_imageCache)
            {
                if (!_imageCache.ContainsKey(imageUrl))
                {
                    _imageCache[imageUrl] = SystemIcons.Error.ToBitmap();
                }
            }

            // 在UI线程上刷新视图
            this.BeginInvoke(new Action(() =>
            {
                gridView1.RefreshData();
            }));
        }

        /// <summary>
        /// 获取图片 - 如果缓存中有则返回缓存中的图片，否则返回null
        /// </summary>
        private Image GetImage(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
                return null;

            // 尝试从缓存获取图片
            lock (_imageCache)
            {
                if (_imageCache.ContainsKey(imageUrl))
                {
                    return _imageCache[imageUrl];
                }
            }

            // 未找到图片，触发加载
            PreloadImage(imageUrl);
            return null;
        }

        /// <summary>
        /// 自定义绘制图片单元格
        /// </summary>
        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            // 只处理图片列
            if (e.Column.FieldName == "Img")
            {
                // 获取单元格的URL
                string imgUrl = e.CellValue as string;
                if (string.IsNullOrEmpty(imgUrl))
                    return;

                // 标记我们将处理单元格绘制
                e.Handled = true;

                // 获取单元格边界
                Rectangle cellBounds = e.Bounds;

                // 获取图片（从缓存或触发加载）
                Image img = GetImage(imgUrl);

                // 如果图片存在，绘制图片
                if (img != null)
                {
                    try
                    {
                        // 计算图片绘制区域（保持纵横比）
                        float ratio = (float)img.Width / img.Height;
                        int height = cellBounds.Height - 4;
                        int width = (int)(height * ratio);

                        // 如果宽度超出单元格宽度，进行调整
                        if (width > cellBounds.Width - 4)
                        {
                            width = cellBounds.Width - 4;
                            height = (int)(width / ratio);
                        }

                        // 计算居中位置
                        int x = cellBounds.X + (cellBounds.Width - width) / 2;
                        int y = cellBounds.Y + (cellBounds.Height - height) / 2;

                        // 绘制图片
                        Rectangle imgRect = new Rectangle(x, y, width, height);
                        e.Graphics.DrawImage(img, imgRect);
                    }
                    catch
                    {
                        // 如果绘制过程中出错，绘制错误文本
                        using (StringFormat sf = new StringFormat())
                        {
                            sf.Alignment = StringAlignment.Center;
                            sf.LineAlignment = StringAlignment.Center;
                            e.Graphics.DrawString("图片错误", e.Appearance.Font, Brushes.Red, cellBounds, sf);
                        }
                    }
                }
                else
                {
                    // 图片还未加载，绘制加载中文本
                    using (StringFormat sf = new StringFormat())
                    {
                        sf.Alignment = StringAlignment.Center;
                        sf.LineAlignment = StringAlignment.Center;
                        e.Graphics.DrawString("加载中...", e.Appearance.Font, Brushes.Gray, cellBounds, sf);
                    }
                }
            }
        }
        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Reset_Click(object sender, EventArgs e)
        {
            // 清空所有查询条件
            txt_code.Text = string.Empty;
            grid_client.EditValue = null;
            time_createat.EditValue = null;

            // 重新加载所有工单数据
            await LoadWorkOrder();

            // 显示第一页数据
            userControl11.CurrentPage = 1;
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";
            DisplayPagedData();
        }
        /// <summary>
        /// 行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        /// <summary>
        /// 点击分配工艺流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Addprocesscilick_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前选中行
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请先选择一条工单记录", "提示");
                    return;
                }

                // 获取当前行的工单数据
                WorkOrderModel model = gridView1.GetRow(rowHandle) as WorkOrderModel;
                if (model == null)
                {
                    XtraMessageBox.Show("无法获取选中的工单数据", "错误");
                    return;
                }

                // 创建参数对象 - 只传递ID
                var parameters = new Dictionary<string, object>
        {
            { "workOrderId", model.Id.ToString() }
        };

                // 使用VuePageManager打开工艺设计页面
                var form = Process.Vue.VuePageManager.OpenVuePage(
                    "/technology-design",  // Vue页面路径
                    parameters,            // 传递参数
                    "工艺流程设计"         // 窗口标题
                );

                // 注册窗口关闭事件，用于在完成设计后刷新数据
                if (form != null)
                {
                    form.FormClosed += async (s, args) =>
                    {
                        if (form.DialogResult == DialogResult.OK)
                        {
                            await LoadWorkOrder();
                            DisplayPagedData();
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开工艺设计页面时出错: {ex.Message}", "错误");
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            // Get the currently selected row
            int rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0)
            {
                XtraMessageBox.Show("请先选择一条工单记录", "提示");
                return;
            }

            // Get the work order data from the selected row
            WorkOrderModel model = gridView1.GetRow(rowHandle) as WorkOrderModel;
            if (model == null)
            {
                XtraMessageBox.Show("无法获取选中的工单数据", "错误");
                return;
            }

            // Check work order state
            if (model.State == "禁用" || model.State == "未启用")
            {
                XtraMessageBox.Show("该工单无法使用", "提示");
                return;
            }

            // Check if step already exists
            if (!string.IsNullOrEmpty(model.step))
            {
                XtraMessageBox.Show("该工单已经存在步骤", "提示");
                return;
            }

            try
            {
                // 显示处理中的提示
                this.Cursor = Cursors.WaitCursor;

                // 创建HttpClientHandler并配置SSL证书验证
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (sender_, cert, chain, sslPolicyErrors) => true // 忽略SSL证书错误
                };

                // 发送请求到指定的API
                using (var client = new HttpClient(handler))
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);

                    // 发送GET请求
                    var response = client.GetAsync($"http://localhost:5179/api/OperationModel/StartWorkflow?Id={model.Id}").Result;

                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"工单[{model.Code}]工作流启动成功！", "成功");
                    }
                    else
                    {
                        XtraMessageBox.Show($"工作流启动失败: {response.ReasonPhrase}", "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"启动工作流时出错: {ex.Message}", "错误");
            }
            finally
            {
                // 恢复鼠标指针
                this.Cursor = Cursors.Default;
            }
        }
    }
}